package commonInfrastructure;

import entity.Department;
import entity.Staff;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@LocalBean
public class DepartmentSessionBean {

    public final String DEPARTMENT_NAME_REQUIRED = "Department name required";
    public final String DUPLICATE_DEPARTMENT_NAME = "Duplicate department name";
    @PersistenceContext
    private EntityManager entityManager;

    public String addDepartment(String name, List<Staff> staff) {
        if (name == null) {
            return DEPARTMENT_NAME_REQUIRED;
        }
         if (getDepartmentByName(name).size() > 0) {
            return DUPLICATE_DEPARTMENT_NAME;
        }
        Department department = new Department();
        department.setName(name);
        department.setStaff(staff);
        entityManager.persist(department);
        entityManager.flush();
        return String.valueOf(department.getId());
    }

    public List<Department> getDepartmentById(Long id) {
        String strQuery = "SELECT d FROM Department d WHERE d.id = :inId";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inId", id);
        return query.getResultList();
    }
    
    public List<Department> getDepartmentByName(String name) {
        String strQuery = "SELECT d FROM Department d WHERE d.name = :inName";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inName", name);
        return query.getResultList();
    }

    public List<Department> getAllDepartments() {
        String strQuery = "SELECT d FROM Department d";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    public void deleteDepartment(Long id) {
        List departments = getDepartmentById(id);
        if (departments.get(0) != null) {
            entityManager.remove(departments.get(0));
            entityManager.flush();
        }
    }

    public void updateDepartment(Long id, String name, List<Staff> staff) {
        Department department = getDepartmentById(id).get(0);
        if (department != null) {
            if(name != null)
                department.setName(name);
            if(staff!= null)
                department.setStaff(staff);
            entityManager.merge(department);
            entityManager.flush();
        }
    }
    
    public void updateDepartmentStaffByName(String name, List<Staff> staff) {
        Department department = getDepartmentByName(name).get(0);
        if (department != null) {
            if(staff!= null)
                department.setStaff(staff);
            entityManager.merge(department);
            entityManager.flush();
        }
    }
    
}
